<?php
/*
---------------------------------------------------------
														+
名称:易通支付通道										+
														+
控制器名称:YiTongController								+
														+
日期:2017-10-11											+
														+
作者:小翁												+
														+
---------------------------------------------------------
*/
namespace Pay\Controller;

use Common\Common\Api\Order;
use Common\Common\Api\Ordermember;

class FupayController extends PayController{
    protected $config;
    protected $key;
    protected $url;

    public function pay($array){
        $this->config = M("Channel")->where(array('id'=>$array['channel']))->find();
        if(!$this->config){
            $this->showmessage('通道错误!',['code'=>'019']);
        }

        $product = M("Product")->where(["id"=> I("request.pay_bankcode","")])->find();
        if(!$product){
            $this->showmessage('未找到支付产品!',['code'=>'020']);
        }

        $parameter = array(
            'code' => $this->config['code'], // 通道名称
            'title' => $this->config['title'],
            'exchange' => 1, // 金额比例
            'gateway' => $this->config['gateway'],
            'orderid' => createOrderId(),
            'out_trade_id' => I("request.pay_orderid"),
            'body' => 'pay',
            'channel'=>$array
        );

        $return = $this->orderadd( $parameter );

        $data = array();
        $data['merchantId'] = $this->config['mch_id'];
        $data['amount'] = $return['amount'];
        $data['orderId'] = $return['orderid'];
        $data['orderTime'] = date("YmdHis",time());
        $data['requestIp'] = $_SERVER['REMOTE_ADDR'];
        $data['goodsName'] = 'propay';
        $data['goodsDesc'] = 'propay';

        $api = '';
        switch($product['paytype']){
            //微信
            case 1:
                $data['service'] = '0002';
                $api = 'onlinepay/scanPayApi';
                break;
            //支付宝
            case 3:
                $data['service'] = '0010';
                $api = 'onlinepay/scanPayApi';
                break;
            //QQ钱包扫码
            case 8:
                $data['service'] = '0015';
                $api = 'onlinepay/scanPayApi';
                break;
            //银联扫码
            case 11:
                $data['service'] = '010800';
                $api = 'onlinepay/scanPayApi';
                break;
            //京东钱包
            case 9:
                $data['service'] = '010700';
                $api = 'onlinepay/scanPayApi';
                break;
            //支付宝H5
            case 4:
                $data['payType'] = '22';
                $api = 'onlinepay/h5PayApi';
                break;
            //微信H5
            case 2:
                $data['payType'] = '30';
                $api = 'onlinepay/h5PayApi';
                break;
            //QQ钱包H5
            case 10:
                $data['payType'] = '31';
                $api = 'onlinepay/h5PayApi';
                break;
            //京东H5
            case 14:
                $data['payType'] = '34';
                $api = 'onlinepay/h5PayApi';
                break;
            //银联快捷
            case 13:
                $data['payType'] = '1005';
                $api = 'onlinepay/unionPayApi';
                break;
            //网银直连
            case 6:
                //网银跳转
            case 5:
                $data['cardType'] = '0';
                $data['payType'] = '1107';
                if(isMobile()){
                    $data['payType'] = '1106';
                }
                $api = 'onlinepay/gatewayPayApi';
                break;
            default:
                $this->showmessage('暂不支持此方式!',['code'=>'020']);

        }
        $data['notifyUrl'] = $return['notifyurl'];
        $data['returnUrl'] = $return['callbackurl'];
		//$data['notifyUrl'] = "http://www.dlbp4.cn/Pay_Fupay_notifyurl";
		//$data['returnUrl'] = "http://www.dlbp4.cn/Pay_Fupay_callbackurl";
		

        ksort($data);
        $str = httpstr($data)."&key=".$this->config['signkey'];
        $data['sign'] = strtoupper(md5($str));

        $apiurl = $this->config['gateway'] . $api;

        switch($product['paytype']){
            //支付宝H5
            case 4:
                //微信H5
            case 2:
                //QQ钱包H5
            case 10:
                //京东H5
            case 14:
                //银联快捷
            case 13:
                //银联快捷
            case 6:
            case 5:
                po($apiurl, $data);
                break;
        }

        $res = curl($apiurl, httpstr($data));

        if(!$res){
            $this->showmessage('请求失败!',['code'=>'020']);
        }
        //保存请求返回
        M("Order")->where([ 'pay_orderid'=>$return['orderid']])->save(["rd_return"=>$res,"request"=>json_encode($data)]);

        $res = json_decode($res, true);
        if(empty($res)){
            $this->showmessage("数据获取错误", ['code'=>'020']);
        }

        /*
         Array
        (
            [code] => 520000
            [sign] => 34411051e3fd1dcd952e2a0233830f0d
            [bankUrl] => https://qr.95516.com/00010000/62511223203127964768248753210411
            [message] => 下单成功
        )
         */
        $code = $res['bankUrl'];

        switch($product['paytype']){
            //银联扫码
            case 11:
                //header("location: {$code}"); exit;
        }

        if(!$code){
            if($res['message']){
                $this->showmessage($res['message'], ['code'=>'020']);
            }
            $this->showmessage("获取二维码失败", ['code'=>'020']);
        }

        $paytype = transArr( C("PAYTYPES"), "id");
        $this->assign("title", $paytype[$this->config['paytype']]);
        $this->assign("return", $return);
        $this->assign("imgurl", C("website.DOMAIN")."/Pay_Qrcode_getCode?data=".urlencode($code));
        $this->display("WeiXin/Pay");
    }

    function curl($apiurl,$data){
        $con = curl_init($apiurl);
        curl_setopt($con, CURLOPT_HEADER, false);
        curl_setopt($con, CURLOPT_POSTFIELDS, $data);
        curl_setopt($con, CURLOPT_POST, true);
        curl_setopt($con, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($con, CURLOPT_TIMEOUT, 10);
        $res = curl_exec($con);
        curl_close($con);

        return $res;
    }

    //通知
    public function notifyurl(){
        //file_put_contents("a.txt",var_export($_POST,true)."\r\n\r\n");
        //file_put_contents("a.txt",var_export($_GET,true."\r\n\r\n"), FILE_APPEND);
        //file_put_contents("a.txt", file_get_contents('php://input')."\r\n\r\n", FILE_APPEND);
        //file_put_contents("a.txt", date('Y-m-d H:i:s',time())."\r\n\r\n", FILE_APPEND);

        $s = file_get_contents('php://input');
        //$s = '{"random":"h520180821130434222742","amount":"500","code":"520000","orderId":"201808211304069311306","sign":"24F846533B30470867FEF765C3E1B579","message":"回调支付成功","status":4}';
        $p = $data = json_decode($s, true);

        if(!$p || empty($p)){
            exit("wrong");
        }
        //echo '<pre/>'; print_r($p);exit;
        /*
        Array
        (
            [random] => h520180821130434222742
            [amount] => 500
            [code] => 520000
            [orderId] => 201808211304069311306
            [sign] => 24F846533B30470867FEF765C3E1B579
            [message] => 回调支付成功
            [status] => 4
        )
         */

        //获取订单信息
        $orderid = $p['orderId'];
        $find = M("Order")->where(array("pay_orderid"=>$orderid))->find();

        if(!$find){
            echo 'order_not_found'; exit;
        }

        //保存回调数据
        M("Order")->where(array("pay_orderid"=>$p['busi_order_no']))->save(array("server_return"=> $s,"pay_orderid_rd"=>$p['random']));
		
        //获取渠道信息
        $this->config = M("Channel")->where(array('code'=>"Fupay"))->find();

        if($p['status'] != 4){
            echo "pail_fail"; exit;
        }

        $sign = $p['sign'];
        unset($p['random']);
        unset($p['sign']);

        ksort($p);
        $str = httpstr($p).'&key='.$this->config['signkey'];
        $sign2 = strtoupper(md5($str));


        if($sign != $sign2){
            exit("fail");
        }

        //处理支付
        $this->EditMoney($find['pay_orderid'],"Fupay",0);
        //回调成功
        echo 'SUCCESS'; exit;
    }

    public function callBackUrl(){

        echo '支付成功'; exit;
    }
}